using System;
using System.Drawing;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;

namespace HWEngine
{
	[Serializable]
	public class MutationTilt : ILetterMutation
	{
		private Random rand = new Random();

		[XmlAttribute("Angle")]
		public float Angle { get; set; }

		[XmlAttribute("Dispersion")]
		public float Dispersion { get; set; }

		[XmlAttribute("Enabled")]
		public bool Enabled { get; set; }

		public MutationTilt()
		{
		}

		public MutationTilt(float angle, float randomShift)
		{
			Angle = angle;
			Dispersion = randomShift;
			Enabled = true;
		}

		public void Mutate(Letter s)
		{
			if (!Enabled) return;

			float shift = (float) (Angle + (rand.NextDouble() - 0.5)*Dispersion);

			float width = 0;
			float height = 0;
			foreach (Line l in s.Lines)
			{
				foreach (PointF p in l.Points)
				{
					if (p.X > width) width = p.X;
					if (p.Y > height) height = p.Y;
				}
			}

			foreach (Line l in s.Lines)
			{
				for (int i = 0; i < l.Points.Count; i++)
				{
					PointF p = l.Points[i];
					p.X += shift*((height - p.Y)/height);
					l.Points[i] = p;
				}
			}
		}

		public void LoadFromXml(XPathNavigator xml)
		{
			Angle = (float) Convert.ToDouble(xml.GetAttribute("Angle", String.Empty), CultureInfo.InvariantCulture);
			Dispersion = (float) Convert.ToDouble(xml.GetAttribute("RandomShift", String.Empty), CultureInfo.InvariantCulture);
			Enabled = Convert.ToBoolean(xml.GetAttribute("Enabled", String.Empty), CultureInfo.InvariantCulture);
		}

		public XmlElement SaveToXml(XmlDocument parentDoc)
		{
			XmlElement el = parentDoc.CreateElement("mutationTilt");
			el.SetAttribute("Angle", Angle.ToString(CultureInfo.InvariantCulture));
			el.SetAttribute("RandomShift", Dispersion.ToString(CultureInfo.InvariantCulture));
			el.SetAttribute("Enabled", Enabled.ToString());
			return el;
		}
	}
}